#include "ratingwidget.h"

RatingWidget::RatingWidget(QByteArray docHash, int rating, QWidget *parent) :
	QLabel(parent), rating(rating), docHash(docHash)
{
	setRating(rating);
}


void RatingWidget::setRating(int rating)
{
	if (this->rating != rating) {
		emit ratingChanged(docHash, rating);
	}
	this->rating = rating;
	setPixmap(QString(":/icons/stars%1.png").arg(rating));
}

int RatingWidget::ratingFromClick(QMouseEvent *ev)
{
	qreal starWidth = pixmap()->width()/3.0;
	int newRating = (ev->posF().x() + starWidth*3.0/4.0)/starWidth;
	newRating = qMin(3, qMax(0, newRating));
	return newRating;
}

void RatingWidget::mousePressEvent(QMouseEvent *ev)
{
	ev->accept();
	if (ev->buttons() & Qt::LeftButton) {
		setRating(ratingFromClick(ev));
	}
}

void RatingWidget::mouseMoveEvent(QMouseEvent *ev)
{
	ev->accept();
	if (ev->buttons() & Qt::LeftButton) {
		setRating(ratingFromClick(ev));
	}
}

void RatingWidget::mouseReleaseEvent(QMouseEvent *ev)
{
	ev->accept();
	if (ev->buttons() & Qt::LeftButton) {
		setRating(ratingFromClick(ev));
	}
}
